package com.ruiysoft.controller.integral;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruiysoft.controller.integral.vo.WxIntegralTradeListVo;
import com.ruiysoft.entity.integral.Integral;
import com.ruiysoft.entity.integral.IntegralCurrent;
import com.ruiysoft.entity.sys.SysMicroShop;
import com.ruiysoft.entity.sys.SysShopPersonnel;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultCode;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.pub.entity.PageInfo;
import com.ruiysoft.service.integral.IIntegralCurrentService;
import com.ruiysoft.service.integral.IIntegralService;
import com.ruiysoft.service.integral.bean.IntegralCondition;
import com.ruiysoft.service.integral.consts.TradeType;
import com.ruiysoft.service.mdse.consts.MdseEnum;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-04-13T19:28:15.988+08:00")

@RestController
public class WxIntegralApiController implements WxIntegralApi {

    private static final Logger log = LoggerFactory.getLogger(WxIntegralApiController.class);


    private final IIntegralService integralService;
    private final IIntegralCurrentService integralCurrentService;

    @org.springframework.beans.factory.annotation.Autowired
    public WxIntegralApiController(IIntegralService integralService, IIntegralCurrentService integralCurrentService) {
        this.integralService = integralService;
        this.integralCurrentService = integralCurrentService;
    }
    private Long getShopId() {
        SysMicroShop shop = LoginContextUtil.instance().getEntryMicroShop();
        return shop.getId();
    }
    private SysShopPersonnel getUser() {
        SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
        return personnel;
    }

    @Override
    public Result<Long> wxIntegralGet() {
        Long shopId = getShopId();
        SysShopPersonnel personnel = getUser();

        try {
            if(StringUtils.isBlank(personnel.getMobile())){
                throw new RuntimeException("未绑定手机号，无法关联账户");
            }

            QueryWrapper qw = integralService.getWapperByCondition(new IntegralCondition()
                    .setShopId(shopId).setPhone(personnel.getMobile()).setIsUse(MdseEnum.IsUseEnum.YES));

            qw = new QueryWrapper<Integral>()
                    .eq("phone", personnel.getMobile())
                    .eq("shop_id", shopId)
                    .eq("is_use",1);

            Integral integral = integralService.getOne(qw);

            return ResultGenerator.genSuccessResult(Optional.ofNullable(integral).map(Integral::getIntegral).orElse(0L));

        } catch (Exception e) {
            log.error("用户查询积分余额--{}--{}",shopId,personnel.getMobile(), e);
            return ResultGenerator.genFailResult(ResultCode.CODE_COMMON_ERROR);
        }
    }

    @Override
    public Result<PageInfo> wxIntegralTradeGet(@NotNull @ApiParam(value = "分页开始页", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页显示多少条数据", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize) {

        Long shopId = getShopId();
        SysShopPersonnel personnel = getUser();
        IntegralCondition condition = new IntegralCondition()
                .setShopId(shopId).setPhone(personnel.getMobile()).setSuperOrderByClause("createtime");
        try {
            IPage<IntegralCurrent> page = integralCurrentService.page(new Page<>(pageStart,pageSize),integralCurrentService.getWapperByCondition(condition));
            List<WxIntegralTradeListVo> list = page.getRecords().stream().filter(Objects::nonNull)
                    .map(a->new WxIntegralTradeListVo().id(a.getId()).integral(a.getIntegral())
                            .tradeTime(Optional.ofNullable(a.getCreatetime()).map(Date::getTime).orElse(null))
                            .tradeType(a.getTradeType())
                            .typeName(Optional.ofNullable(TradeType.getEnum(a.getTradeType())).map(TradeType::getName).orElse(""))
                    ).collect(Collectors.toList());
            return ResultGenerator.genSuccessResult(new PageInfo<WxIntegralTradeListVo>(list, (Page) page));
        } catch (Exception e) {
            log.error("用户查询积分记录--{}--{}",shopId, JSONObject.toJSONString(condition), e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

}
